package com.kgc.travel.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author: Mxj
 * @date: 2020/12/22 20:28
 * @description:
 */
public class MyMD5 {

    static char[] hex = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};


    /**
     * @param pwd 加密的字符串例如密码
     * @return 返回加密后的字符串
     * 使用方法：  String pwd = MyMD5.MD5(加密字符串);
     */
    public static String MD5(String pwd) {
        String newpwd = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(pwd.getBytes());
            newpwd = (String)byte2str(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return newpwd;
    }


    /**
     * 将字节数组转换成十六进制字符串
     * @param bytes
     * @return
     */
    private static String byte2str(byte []bytes){
        int len = bytes.length;
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < len; i++) {
            byte byte0 = bytes[i];
            result.append(hex[byte0 >>> 4 & 0xf]);
            result.append(hex[byte0 & 0xf]);
        }
        return result.toString();
    }

}
